/*
 * Copyright (c) 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.libermundi.theorcs.core.tapestry.model;

import java.util.Arrays;
import java.util.Collection;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.libermundi.theorcs.core.model.freemarker.Template;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

public abstract class AbstractFreemarkerTemplate implements Template {
	private static final long serialVersionUID = -5275581014144738323L;
	private final Collection<String> _mandatoryParams;
	private final Map<String,Object> _optionnalParams;
	
	public AbstractFreemarkerTemplate(){
		_mandatoryParams = Lists.newArrayList();
		_optionnalParams = Maps.newHashMap();
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.libermundi.theorcs.core.model.freemarker.Template#getMandatoryParams()
	 */
	@Override
	public Collection<String> getMandatoryParams() {
		return _mandatoryParams;
	}

	/*
	 * (non-Javadoc)
	 * @see org.libermundi.theorcs.core.model.freemarker.Template#getOptionnalParams()
	 */
	@Override
	public Map<String, Object> getOptionnalParams() {
		return _optionnalParams;
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.libermundi.theorcs.core.model.freemarker.Template#checkConsistency(java.util.Map)
	 */
	@Override
	public void checkConsistency(Map<String, Object> parameters) throws IllegalArgumentException {
		Collection<String> params =  parameters.keySet();
		if(!CollectionUtils.isSubCollection(_mandatoryParams,params)){
			String missing = Arrays.toString(CollectionUtils.subtract(_mandatoryParams, params).toArray());
			throw new IllegalArgumentException("There are some missing mandatory parameters : " + missing);
		}
	}	
	
	protected void addParam(String param) {
		addParam(param,Boolean.TRUE,null);
	}

	protected void addParam(String param, Object defaultValue) {
		addParam(param,Boolean.FALSE,defaultValue);
	}
	
	private void addParam(String param, boolean mandatory, Object defaultValue) {
		if(mandatory){
			_mandatoryParams.add(param);
		} else {
			assert defaultValue != null : "Default Value for Optional Parameter cannot be null";
			_optionnalParams.put(param, defaultValue);
		}
	}
}
